from django.http import HttpResponse ,JsonResponse,response
from django.shortcuts import render ,HttpResponseRedirect,redirect
import model.StudentDao as stuDao
import model.userDao  as userDao
import model.student as stu
import json
import model.user as User
import model.util_conn as util
from copy import deepcopy

def index(request):
    util.send_news(new="微信通知初始化....")
    return HttpResponseRedirect("home/login")
# 系统主界面。
def login(request):
    return render(request,"login.html")

# 处理登录请求，返回学生信息管理界面，可以对学生进行增删查改操作
def inlogin(request):
    if request.method == "POST":
        name=request.POST['userNameOrEmailAddress']
        passwd = request.POST['password']
        dao = userDao.userDao()
        data = dao.findByNameAndPasswd(name, passwd)
        if data==None :
            return HttpResponse("用户名或密码错误")
        else:
            user = User.user(data[0], data[1], data[2])
            request.session['name'] =user.name
            request.session['passwd']=user.passwd
            # util.send_news(user=user.name,out=False)
            return HttpResponseRedirect("/home")
    else:
        if (request.session.name==None):
            return HttpResponseRedirect("/home/login")

# 注销登录，退出登录状态，返回登录界面。
def outlogin(request):

    name = request.session['name']
    request.session.clear()
    util.send_news(user=name,out=True)
    return redirect("login.html")

def home(request):
    return render(request,"home.html")

# 处理查询管理员信息，返回所有的管理员信息，该界面只有超级用户admin可以登录，对管理员进行操作
def select_user(request):
    if request.method == "GET":
        dao = userDao.userDao()
        users = dao.findAllUser()
        items=[]
        for user in users:
            for i,k in enumerate(user):
                if i==0:
                    item={"主键ID":k}
                elif i==1:
                    item["用户名"]=str(k)
                else:
                    item["密码"] = str(k)
            items.append(item)
            content = json.dumps(items,ensure_ascii = False)
        return HttpResponse(content)


# 查询学生信息操作，返回学生信息，json数据类型
def select_stu(request):
    if request.method == "GET":
        dao = stuDao.StudentDao()
        students = dao.findAllStudent()
        print(students)
        items=[]
        for stu in students:
            for i,s in enumerate(stu):
                if i==0:
                    item={"id":s}
                elif i==1:
                    item["name"]=str(s)
                elif i==2:
                    item["age"] = s
                elif i==3:
                    item['sex']=str(s)
                else:
                    item["grade"]=str(s)
            items.append(item)
            content = json.dumps(items,ensure_ascii = False)
        return HttpResponse(content)


# 处理add添加学生信息的逻辑处理，如果是get，则返回添加学生的信息的界面，给管理员进行填写
# 如果的post请求，则把提交的信息存到数据库中，回到主界面。
def add(request):
    if request.method=="GET":
        return  render(request,"add.html")
    elif request.method=="POST":
        dao = stuDao.StudentDao()
        name = request.POST["name"]
        sid = 1
        age = request.POST["age"]
        sex = request.POST["sex"]
        grade = request.POST["grade"]
        stu1 = stu.student(stu_name=name, stu_age=age, stu_gender=sex, stu_grade=grade)
        dao.save(stu1)
        util.send_news(new="添加了学生"+name)
        return HttpResponseRedirect("/home")

# 根据浏览器发来的get请求，id号进行删除学生信息。
def delete(request):
    if request.method == "GET":
        dao = stuDao.StudentDao()
        id = request.GET["id"]
        student = dao.findByID(id)
        print(student)
        util.send_news(new="移除了学生" + student[1])
        dao.delete(id)
    return HttpResponseRedirect("/home")

# 查询用户界面，
def user(request):
    return render(request,"show_user.html")

# 编辑修改的学生信息，
def modify(request):
    id = request.GET['id']
    dao = stuDao.StudentDao()
    data = dao.findByID(id)
    request.id  = data[0]
    request.name = data[1]
    request.age  = data[2]
    request.sex = data[3]
    request.grade = data[4]
    util.send_news(new="正在修改学生"+data[1] )
    return render(request,"modify.html")

# 提交到服务器，修改完成
def update(request):
    if request.method=="POST":
        id = request.POST["sid"]
        name = request.POST["name"]
        age = request.POST["age"]
        sex = request.POST["sex"]
        grade = request.POST["grade"]
        st = stu.student(stu_id=id,stu_name=name,stu_age=age,stu_gender=sex,stu_grade=grade)
        dao = stuDao.StudentDao()
        student = dao.findByID(id)
        util.send_news(new="学生" + student[1]+"的信息已被修改")
        dao.update(st)
        return HttpResponseRedirect("/home")

#  返回图形的用户端界面。
def graph(request):

    util.send_news(new="查看了图形显示区")
    return render(request,"show_grph.html")

# 返回给客户端数据ajax信息。
def senddata(request):
    if request.method == "GET":
        dao = stuDao.StudentDao()
        data = dao.findAllStudent()
        temp={}
        item={}
        items=[]
        for i in data:
            if i[4]  not in temp:
                temp[i[4]]=1
            else:
                temp[i[4]] += 1
        for key in temp:
            item["name"]=key
            item["value"]=temp.get(key)
            items.append(item)
            item = deepcopy(item)
        content = json.dumps(items, ensure_ascii=False)
        return HttpResponse(content)
